package com.nf.health.app.activity.global;

import android.Manifest;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.LocalBroadcastManager;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.android.volley.VolleyError;
import com.hyphenate.EMConnectionListener;
import com.hyphenate.EMError;
import com.hyphenate.EMMessageListener;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMConversation;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.easeui.controller.EaseUI;
import com.hyphenate.easeui.domain.EaseUser;
import com.hyphenate.exceptions.HyphenateException;
import com.hyphenate.util.NetUtils;
import com.lling.photopicker.utils.LogUtils;
import com.nf.health.app.AppModel;
import com.nf.health.app.Constants;
import com.nf.health.app.MyApplication;
import com.nf.health.app.R;
import com.nf.health.app.activity.intervene.NoDataInterveneFragment;
import com.nf.health.app.chatservice.activity.ChatActivity;
import com.nf.health.app.core.HttpActionHandle;
import com.nf.health.app.datamain.fragment.MainDataFragment;
import com.nf.health.app.fragment.ConversationListFragment;
import com.nf.health.app.homepage.fragment.MainNewHomeFragment;
import com.nf.health.app.http.RequestProvider;
import com.nf.health.app.inquiry.bean.ChangeFragmentBean;
import com.nf.health.app.login.activity.LoginActivity;
import com.nf.health.app.mine.fragment.MainMineFragment;
import com.nf.health.app.models.ChatMessageVo;
import com.nf.health.app.models.UpdateVo;
import com.nf.health.app.utils.ActivityUtils;
import com.nf.health.app.utils.AppManager;
import com.nf.health.app.utils.AppUtil;
import com.nf.health.app.utils.ContorlViewUtils;
import com.nf.health.app.utils.DensityUtil;
import com.nf.health.app.utils.FileHelper;
import com.nf.health.app.utils.JsonUtils;
import com.nf.health.app.utils.LogUtil;
import com.nf.health.app.utils.PreferenceHelper;
import com.nf.health.app.utils.ScreentUtils;
import com.nf.health.app.utils.Util;
import com.nf.health.app.widget.ShowDialogFactory;
import com.tbruyelle.rxpermissions.RxPermissions;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;

import rx.functions.Action1;
//					 _ooOoo_  
//					o8888888o  
//					88" . "88  
//					(| -_- |)  
//					 O\ = /O  
//				 ____/`---'\____  
//			   .'  \\|     |//  `.  
//			  /  \\|||  :  |||//  \  
//			 /  _||||| -:- |||||-  \  
//			 |   |  \\\ - ///  |   |  
//			 | \_|  ''\---/''  |   |  
//			 \   .-\__ `-` ___/-.  /  
//			___`. .' /--.--\ `. . __  
//       ."" '< `.___\_<|>_/___.' >'"".  
//		| | : `- \`.;`\ _ /`;.`/ - ` : | |  
//		  \ \ `-. \_ __\ /__ _/ .-` / /  
//======`-.____`-.___\_____/___.-`____.-'======  
//					 `=---='  
//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
//
//.............................................  
//				佛祖保佑             永无BUG 
//		佛曰:
//			写字楼里写字间，写字间里程序员；  
//			程序人员写程序，又拿程序换酒钱。  
//			酒醒只在网上坐，酒醉还来网下眠；  
//			酒醉酒醒日复日，网上网下年复年。  
//			但愿老死电脑间，不愿鞠躬老板前；  
//			奔驰宝马贵者趣，公交自行程序员。  
//			别人笑我忒疯癫，我笑自己命太贱；  
//			不见满街漂亮妹，哪个归得程序员？

/**
 * @author LGS
 */
public class MainActivity extends FragmentActivity implements OnCheckedChangeListener, HttpActionHandle {
    private final String GET_INQUIRY_MARK = "get_inquiry_mark";
    public static final String CLOSE_DIALOG = "com.close.sgow.dialog";
    private static final java.lang.String TAG = MainActivity.class.getSimpleName();
    /**
     * 升级时间
     */
    private String KEY_UPDATE_TIME = "updateTodayTime";
    /**
     * 记录按下的页签索引
     */
    private int index;
    /**
     * 按下下一个页签前，当前显示的页签
     */
    private int currentTabIndex;
    // private Fragment[] fragments;

    private RadioGroup rg_footer_navigator;
    private RadioButton rb_footer_home;
    private RadioButton rb_footer_regimen;
    private RadioButton rb_footer_data;
    private RadioButton rb_footer_my;
    // private RadioButton rb_footer_intervene;//干预
    private AlertDialog dialog;
    private long backTime;
    private MainNewHomeFragment mainHomeFragment = null;//首页
    private ConversationListFragment conversationListFragment = null;//消息
    private NoDataInterveneFragment noDataInterveneFragment = new NoDataInterveneFragment();//干预
    private MainDataFragment mainDataFragment = null;//数据
    private MainMineFragment mainMineFragment = null;//我的
    private RequestProvider provider;
    private LocalBroadcastManager broadcastManager;
    private BroadcastReceiver broadcastReceiver;

    private boolean isConflictDialogShow;
    private TextView tvUnredMsg;
    private TextView tvUnredMsgInquiry;
    private ShowDialogFactory dialogFactory;
    private FragmentManager fragmentManager;// 用于对Fragment进行管理
    private FragmentTransaction transaction;
    private static final int index_first_tag = 0;// 首页
    private static final int index_second_tag = 1;// 消息
    private static final int index_third_tag = 2;// 数据
    private static final int index_four_tag = 3;// 我的
    private static final int index_five_tag = 4;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        LogUtil.e(TAG, "session: " + PreferenceHelper.getString(PreferenceHelper.NF_USER_SESSION, "") + "save=" + savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_main);
        getWindow().setBackgroundDrawable(null);//
        ViewGroup contentFrameLayout = (ViewGroup) findViewById(Window.ID_ANDROID_CONTENT);
        View parentView = contentFrameLayout.getChildAt(0);
        if (parentView != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            parentView.setFitsSystemWindows(false);
        } else {
            parentView.setFitsSystemWindows(true);
        }
        EventBus.getDefault().register(this);
        AppManager.getAppManager().addActivity(this);
        initData();
        fillView();
        //注册local广播接收者，用于接收demohelper中发出的群组联系人的变动通知
        registerBroadcastReceiver();

        checkUpdate();

        EMClient.getInstance().addConnectionListener(emConnectionListener);
        EMClient.getInstance().chatManager().addMessageListener(messageListener);

        new Thread(new Runnable() {
            @Override
            public void run() {
                AppModel.getInstatnce().getContactList();
            }
        }).start();
        //if(Util.isLogin()){
        String yindao = PreferenceHelper.getString(PreferenceHelper.DATAYINDAO, "");
//        if (TextUtils.isEmpty(yindao)) {//第一次进入不操作
//
//        } else {
//            provider.getTopImages(REQUEST_GETTOPIMAGES);
//        }
        initFragmentManager();
        if (savedInstanceState != null) {
            setTabSelection(savedInstanceState.getInt("tab", currentTabIndex));
        } else {
            setTabSelection(currentTabIndex);
        }

        registerReceiver();
        //}
    }

    private void initFragmentManager() {//初始化Fragment的管理器
        fragmentManager = getSupportFragmentManager();
    }

    private void initData() {
        FileHelper.creatDir(Constants.BasePath);
        FileHelper.creatDir(Constants.FileCachePath);
        FileHelper.creatDir(Constants.ImageCachePath);
        FileHelper.creatDir(Constants.DOWNLOADPath);
        provider = new RequestProvider(this);
    }

    private void fillView() {
        rg_footer_navigator = (RadioGroup) findViewById(R.id.rg_footer_navigator);
        rb_footer_home = (RadioButton) findViewById(R.id.rb_footer_home);
        rb_footer_regimen = (RadioButton) findViewById(R.id.rb_footer_regimen);
        rb_footer_data = (RadioButton) findViewById(R.id.rb_footer_data);
        rb_footer_my = (RadioButton) findViewById(R.id.rb_footer_my);
        // rb_footer_intervene = (RadioButton) findViewById(R.id.rb_footer_intervene);
        tvUnredMsg = (TextView) findViewById(R.id.tv_unread_msg);
        tvUnredMsgInquiry = (TextView) findViewById(R.id.tv_unread_msg_inquiry);
        //代码设置环信小红点位置
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(DensityUtil.dip2px(MainActivity.this, 7), DensityUtil.dip2px(MainActivity.this, 7));
        params.leftMargin = (int) (ScreentUtils.getScreenWidth(this) / 3.1);
        params.topMargin = DensityUtil.dip2px(this, 5);
        tvUnredMsg.setLayoutParams(params);

        //代码设置问诊(我的)小红点位置
        RelativeLayout.LayoutParams params2 = new RelativeLayout.LayoutParams(DensityUtil.dip2px(MainActivity.this, 7), DensityUtil.dip2px(MainActivity.this, 7));
        params2.leftMargin = (int) (ScreentUtils.getScreenWidth(this) / 1.12);
        params2.topMargin = DensityUtil.dip2px(this, 5);
        tvUnredMsgInquiry.setLayoutParams(params2);
        rg_footer_navigator.setOnCheckedChangeListener(this);
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (event.getKeyCode() == KeyEvent.KEYCODE_BACK
                && event.getAction() == KeyEvent.ACTION_DOWN) {
            long currentTime = System.currentTimeMillis();
            if (backTime == 0
                    || (backTime != 0 && (currentTime - backTime) > 2 * 1000)) {
                backTime = currentTime;
                Toast.makeText(this, "再按一次返回将退出程序", Toast.LENGTH_SHORT).show();
                return true;
            }
            AppManager.getAppManager().finishAllActivity();
            return true;
        }
        return super.dispatchKeyEvent(event);
    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        if (checkedId != R.id.rb_footer_home) {
            if (!checkRegister()) {
                resetRadioButton(0);
                return;
            }
        }
        switch (checkedId) {
            case R.id.rb_footer_home:
                index = 0;
                setTabSelection(index);
                break;
            case R.id.rb_footer_regimen:

                index = 1;
                setTabSelection(index);
                break;
            case R.id.rb_footer_data:
                index = 2;
                setTabSelection(index);
                break;
            case R.id.rb_footer_my:
                index = 3;
                setTabSelection(index);
                break;
        }

    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
//        super.onSaveInstanceState(outState);//注释掉为了防止fragment重叠 影响其他????2016/11.28
        outState.putInt("tab", currentTabIndex);
    }

    /**
     * 重置选中的button 不要修改了,否则引起其他的bug
     *
     * @param index
     */
    private void resetRadioButton(int index) {
        switch (index) {
            case 0:
                rb_footer_home.setChecked(true);
                break;
            case 1:
                rb_footer_regimen.setChecked(true);
                break;
           /* case 2:
                rb_footer_intervene.setChecked(true);
                break;*/
            case 2:
                rb_footer_data.setChecked(true);
                break;
            case 3:
                rb_footer_my.setChecked(true);
                break;
            default:
                break;
        }
    }

    /**
     * 检测是否已注册
     */
    public boolean checkRegister() {
        String username = PreferenceHelper.getString(PreferenceHelper.USERNAME, "");
        if (!TextUtils.isEmpty(username)) {
            //TODO 测试账号只有3位
            boolean isLogin = PreferenceHelper.getBoolean(PreferenceHelper.ISLOGIN, true);
            if (isLogin) {
                return isLogin;
            } else {
                ActivityUtils.showActivity(this, LoginActivity.class);
                return isLogin;
            }
        } else {
            ActivityUtils.showActivity(this, LoginActivity.class);
            return false;
        }
    }

    /**
     * 根据传入的index参数来设置选中的tab页。
     */
    private void setTabSelection(int index) {
        // 开启一个Fragment事务
        transaction = fragmentManager.beginTransaction();
        // 先隐藏掉所有的Fragment，以防止有多个Fragment显示在界面上的情况
        hideFragments(transaction);
        switch (index) {
            case index_first_tag://首页(消息页)
                if (mainHomeFragment == null) {
                    mainHomeFragment = new MainNewHomeFragment();
                    transaction.add(R.id.ii_middle, mainHomeFragment);
                } else {
                    transaction.show(mainHomeFragment);
                }
                break;
            case index_second_tag://消息
                if (conversationListFragment == null) {
                    conversationListFragment = new ConversationListFragment();
                    transaction.add(R.id.ii_middle, conversationListFragment);
                } else {
                    transaction.show(conversationListFragment);
                }
                break;
            case index_third_tag://数据
                if (mainDataFragment == null) {
                    mainDataFragment = new MainDataFragment();
                    transaction.add(R.id.ii_middle, mainDataFragment);
                } else {
                    transaction.show(mainDataFragment);
                }
                break;
            case index_four_tag://我的
                if (mainMineFragment == null) {
                    mainMineFragment = new MainMineFragment();
                    transaction.add(R.id.ii_middle, mainMineFragment);
                } else {
                    transaction.show(mainMineFragment);
                }
                break;
        }
        transaction.commitAllowingStateLoss();
    }

    /**
     * 将所有的Fragment都置为隐藏状态。
     *
     * @param transaction 用于对Fragment执行操作的事务
     */
    private void hideFragments(FragmentTransaction transaction) {
        if (mainHomeFragment != null) {
            transaction.hide(mainHomeFragment);
        }
        if (conversationListFragment != null) {
            transaction.hide(conversationListFragment);
        }
        if (mainDataFragment != null) {
            transaction.hide(mainDataFragment);
        }
        if (mainMineFragment != null) {
            transaction.hide(mainMineFragment);
        }
    }

    @Override
    public void onAttachFragment(Fragment fragment) {
        // TODO Auto-generated method stub
        super.onAttachFragment(fragment);
        if (mainHomeFragment == null && fragment instanceof MainNewHomeFragment) {
            mainHomeFragment = (MainNewHomeFragment) fragment;
        } else if (conversationListFragment == null && conversationListFragment instanceof ConversationListFragment) {
            conversationListFragment = (ConversationListFragment) fragment;
        } else if (mainDataFragment == null && mainDataFragment instanceof MainDataFragment) {
            mainDataFragment = (MainDataFragment) fragment;
        } else if (mainMineFragment == null && mainMineFragment instanceof MainMineFragment) {
            mainMineFragment = (MainMineFragment) fragment;
        }

    }


    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        LogUtils.e(TAG, "onNewIntent");
        setIntent(intent);

        String msg = getIntent().getStringExtra("msg");
        if (!TextUtils.isEmpty(msg)) {
            showRemindDialog(msg);
        }

        if (getIntent().getBooleanExtra("conflict", false) && !isConflictDialogShow) {
            showConflictDialog();
        }
    }

    private void showRemindDialog(String msg) {
        Builder builder = new Builder(this);
        if (dialog != null) {
            dialog.dismiss();
            dialog = null;
        } else {
            dialog = builder.setTitle("提示").setMessage(msg)
                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                            dialog = null;
                        }
                    })
                    .show();

        }
    }

    //每日首次检测更新

    private void checkUpdate() {
        //每日首次检测更新
        if (Util.isLogin()) {
//            Time t = new Time();
//            t.setToNow();
//            final String str = t.year + "年" + (t.month + 1) + "月" + t.monthDay + "日";
//            final String nowtime = PreferenceHelper.getString(KEY_UPDATE_TIME, "");
//            if (!nowtime.equals(str)) {
//                //当天第一次进入提示
//                //延迟两秒检测更新
//                new Handler().postDelayed(new Runnable() {
//                    @Override
//                    public void run() {
//                        provider.CheckVersionNum("CheckVersionNum");
//                    }
//                }, 2000);
//                PreferenceHelper.putString(KEY_UPDATE_TIME, str);
//            }

            provider.CheckVersionNum("CheckVersionNum");//测试用,每次都检测
        }
    }

    @Override
    public void handleActionSuccess(String actionName, Object object) {
        if (actionName.equals("CheckVersionNum")) {
            final UpdateVo updateVo = (UpdateVo) object;
            if (Float.valueOf(updateVo.getVersion()) > AppUtil.getVersion(this)) {
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setTitle("升级提示");
                builder.setMessage(updateVo.getMsg())
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                //下载需要写SD卡权限, targetSdkVersion>=23 需要动态申请权限,华为p9 7.0 emui5.0没有不行
                                RxPermissions.getInstance(MainActivity.this)
                                        // 申请权限
                                        .request(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                                        .subscribe(new Action1<Boolean>() {
                                            @Override
                                            public void call(Boolean granted) {
                                                if (granted) {
                                                    ContorlViewUtils.updaAppFromService(updateVo.getDownloadurl(), MainActivity.this);
                                                } else {
                                                    // 请求失败回收当前服务
                                                    System.out.println("权限失败");
                                                }
                                            }
                                        });
                            }
                        })
                        .setNegativeButton("取消", null).show();
            }
        } else if (GET_INQUIRY_MARK.equals(actionName)) {
            //检查问诊红点
            String result = (String) object;
            String isMark = JsonUtils.getFiledData(result, "ismark");
            if ("1".equals(isMark) && currentTabIndex != 3) {
                tvUnredMsgInquiry.setVisibility(View.VISIBLE);
            } else {
                tvUnredMsgInquiry.setVisibility(View.INVISIBLE);
            }
        }
    }

    @Override
    public void handleActionStart(String actionName, Object object) {
    }

    @Override
    public void handleActionFinish(String actionName, Object object) {
    }

    @Override
    public void handleActionError(String actionName, String response, VolleyError error) {
    }

    @Override
    protected void onDestroy() {
        AppManager.getAppManager().finishActivity(this);
        unregisterBroadcastReceiver();
        EMClient.getInstance().removeConnectionListener(emConnectionListener);
        EMClient.getInstance().chatManager().removeMessageListener(messageListener);
        MyApplication.getRefWatcher(this).watch(this);
        if (receiver != null) {
            unregisterReceiver(receiver);
        }
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }


    @Override
    protected void onResume() {
        super.onResume();
        provider.getInquiryMark(GET_INQUIRY_MARK);
    }

    EMMessageListener messageListener = new EMMessageListener() {

        @Override
        public void onMessageReceived(List<EMMessage> messages) {
            // 提示新消息
            for (EMMessage message : messages) {
                String currentActivity = AppUtil.getRunningActivityName(MainActivity.this);
                //不是聊天界面给出弹窗
                if (!currentActivity.contains(ChatActivity.class.getSimpleName())) {
                    EaseUI.getInstance().getNotifier().onNewMsg(message);
                }
                //通知
                try {
                    EaseUser user = new EaseUser(message.getFrom());
                    String name = message.getStringAttribute(Constants.EMContact.EF_USERNAME);
                    String himg = message.getStringAttribute(Constants.EMContact.EF_USERICON);
                    user.setNick(name);
                    user.setAvatar(himg);
                    AppModel.getInstatnce().saveContact(user);
                } catch (HyphenateException e) {
                    e.printStackTrace();
                }
            }
            refreshUIWithMessage();
        }

        @Override
        public void onCmdMessageReceived(List<EMMessage> messages) {
            LogUtil.i(TAG, "onCmdMessageReceived");
            //TODO 接受透传消息，对快速提问的回答，根据eid获取查找到数据库的消息，发送文本

        }

        @Override
        public void onMessageReadAckReceived(List<EMMessage> messages) {
            LogUtil.i(TAG, "onMessageReadAckReceived");
        }

        @Override
        public void onMessageDeliveryAckReceived(List<EMMessage> message) {

            LogUtil.i(TAG, "onMessageDeliveryAckReceived");
        }

        @Override
        public void onMessageChanged(EMMessage message, Object change) {
            LogUtil.i(TAG, "onMessageChanged");
        }
    };

    private void refreshUIWithMessage() {
        runOnUiThread(new Runnable() {
            public void run() {
                // 刷新bottom bar消息未读数
                updateUnreadLabel();
                if (currentTabIndex == 1) {
                    // 当前页面如果为聊天历史页面，刷新此页面
                    if (conversationListFragment != null) {
                        conversationListFragment.refresh();
                    }
                }
            }
        });
    }

    private void registerBroadcastReceiver() {
        broadcastManager = LocalBroadcastManager.getInstance(this);
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Constants.ACTION_CONTACT_CHANAGED);
        intentFilter.addAction(Constants.ACTION_GROUP_CHANAGED);
        intentFilter.addAction(CLOSE_DIALOG);
        broadcastReceiver = new BroadcastReceiver() {

            @Override
            public void onReceive(Context context, Intent intent) {
                updateUnreadLabel();
//				updateUnreadAddressLable();
                if (currentTabIndex == 1) {
                    // 当前页面如果为聊天历史页面，刷新此页面
                    if (conversationListFragment != null) {
                        conversationListFragment.refresh();
                    }
                }
                String action = intent.getAction();
                if (action.equals(CLOSE_DIALOG)) {
                    if (dialogFactory != null) {
                        if (dialogFactory.isShowing()) {
                            dialogFactory.dismiss();
                        }
                    }
                }
                /*if(action.equals(Constant.ACTION_GROUP_CHANAGED)){
                    if (EaseCommonUtils.getTopActivity(MainActivity.this).equals(GroupsActivity.class.getName())) {
						GroupsActivity.instance.onResume();
					}
				}*/
            }


        };
        broadcastManager.registerReceiver(broadcastReceiver, intentFilter);
    }

    private void unregisterBroadcastReceiver() {
        broadcastManager.unregisterReceiver(broadcastReceiver);
    }


    /**
     * 连接监听listener
     */
    public EMConnectionListener emConnectionListener = new EMConnectionListener() {

        @Override
        public void onConnected() {

        }

        @Override
        public void onDisconnected(final int error) {
            final String st1 = getResources().getString(R.string.can_not_connect_chat_server_connection);
            final String st2 = getResources().getString(R.string.the_current_network);
            runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    if (error == EMError.USER_REMOVED) {
                        // 显示帐号已经被移除
//                        showAccountRemovedDialog();
                    } else if (error == EMError.USER_LOGIN_ANOTHER_DEVICE) {
                        // 显示帐号在其他设备登陆dialog
                        showConflictDialog();
                    } else {
                        if (NetUtils.hasNetwork(MainActivity.this)) {
                            //连接不到聊天服务器
                        } else {
                            //当前网络不可用，请检查网络设置
                        }
                    }
                }
            });
        }
    };

    /**
     * 显示帐号在别处登录dialog
     */
    private void showConflictDialog() {
        isConflictDialogShow = true;
        EMClient.getInstance().logout(true, null);
        String st = getResources().getString(R.string.Logoff_notification);
        if (!MainActivity.this.isFinishing()) {

            //mLeScanCallback 将搜索结果添加到集合中
            new MaterialDialog.Builder(this)
                    .title(R.string.Logoff_notification)
                    .content(com.hyphenate.easeui.R.string.connect_conflict)
                    .positiveText(R.string.ok)
                    .cancelable(false)
                    .onPositive(new MaterialDialog.SingleButtonCallback() {
                        @Override
                        public void onClick(MaterialDialog dialog, DialogAction which) {
                            finish();
                            startActivity(new Intent(MainActivity.this, LoginActivity.class));
                        }
                    })
                    .show();
        }
    }

    /**
     * 刷新未读消息数
     */
    public void updateUnreadLabel() {
        int count = getUnreadMsgCountTotal();
        if (count > 0) {
//            tvUnredMsg.setText(String.valueOf(count)); //不显示数字了
            tvUnredMsg.setVisibility(View.VISIBLE);
        } else {
            tvUnredMsg.setVisibility(View.INVISIBLE);
        }
    }

    /**
     * 获取未读消息数
     *
     * @return
     */
    public int getUnreadMsgCountTotal() {
        int unreadMsgCountTotal = 0;
        int chatroomUnreadMsgCount = 0;
        unreadMsgCountTotal = EMClient.getInstance().chatManager().getUnreadMsgsCount();
        for (EMConversation conversation : EMClient.getInstance().chatManager().getAllConversations().values()) {
            if (conversation.getType() == EMConversation.EMConversationType.ChatRoom)
                chatroomUnreadMsgCount = chatroomUnreadMsgCount + conversation.getUnreadMsgCount();
        }
        return unreadMsgCountTotal - chatroomUnreadMsgCount;
    }


    /**
     * 控制底部button是否可点击,为了解决我的引导页面显示到其他fragment问题
     *
     * @param isClickable
     */
    public void makeFootButtonState(boolean isClickable) {
        rb_footer_home.setClickable(isClickable);
        rb_footer_regimen.setClickable(isClickable);
        rb_footer_data.setClickable(isClickable);
        rb_footer_my.setClickable(isClickable);
    }


    private CompleteReceiver receiver;

    /**
     * 注册监听APK下载完成的广播
     */
    private void registerReceiver() {
        IntentFilter filter = new IntentFilter();
        filter.addAction(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
        filter.addAction(DownloadManager.ACTION_NOTIFICATION_CLICKED);
        receiver = new CompleteReceiver();
        registerReceiver(receiver, filter);
    }

    private DownloadManager downloadManager;

    class CompleteReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();

            downloadManager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
            if (action.equals(DownloadManager.ACTION_DOWNLOAD_COMPLETE)) {
                long id = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, 0);
                // TODO 判断这个id与之前的id是否相等，如果相等说明是之前的那个要下载的文件
                int download_id = Integer.parseInt(PreferenceHelper.getString("download_id", ""));
                if (id == download_id) {
                    DownloadManager.Query query = new DownloadManager.Query();
                    query.setFilterById(id);
                    Cursor cursor = downloadManager.query(query);
                    int column = cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_LOCAL_FILENAME);
                    if (cursor.moveToNext()) {
                        String path = cursor.getString(column);
                        if (!TextUtils.isEmpty(path)) {
                            AppUtil.installAPK(MainActivity.this, path);
                        }
                    }
                }

            } else if (action.equals(DownloadManager.ACTION_NOTIFICATION_CLICKED)) {
//                showToast("点击通知了");
                //这里取消下载
                downloadManager.remove(Integer.parseInt(PreferenceHelper.getString("download_id", "")));
            }
        }
    }

    /**
     * 接收EventBus消息,改变显示的fragment
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void changeFragment(ChangeFragmentBean bean) {
        index = bean.showIndex;
        resetRadioButton(index);
        setTabSelection(index);
    }

    //接收医生发来的消息
    @Subscribe(threadMode = ThreadMode.MAIN) //在ui线程执行
    public void onDoctorReply(ChatMessageVo message) {
        provider.getInquiryMark(GET_INQUIRY_MARK);
    }
}


